<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * 标
 * @author chenhuan
 *
 */
class Borrow extends CI_Controller {

    function __construct() {
        parent::__construct();
    }
    public function guide(){
        $vdata['active'] = "borrow";
        $vdata['title'] = "猪八借" . ' - ' . CON_KEYWORDS;
        $this->load->view('borrow/borrow_guide',$vdata);
    }
    function borrow_common() {
        //媒体报道
        $this->load->model('Borrow_model');

        $this->load->model('site_model');
        $this->load->model('article_model');
        $meitisite = $this->site_model->get_site_one(array('url' => 'media'));
        $mparms['where']['nid'] = $meitisite['id'];
        $vdata['meiti_list'] = $this->article_model->get_article_list_index_limit($mparms);

        //理财资讯
        $newssite = $this->site_model->get_site_one(array('url' => 'lcnews'));
        if ($newssite['id'] > 0) {
            $nparms['where']['nid'] = $newssite['id'];
            $vdata['lcnews_list'] = $this->article_model->get_article_list_index_limit($nparms);
        }

        //理财风云榜
        $month_rank = $this->Borrow_model->index_total(0); //获取月排名
        $vdata['month_rank'] = $month_rank;

        $total_rank = $this->Borrow_model->index_total(5); //获取累计排名
        $vdata['total_rank'] = $total_rank;

        //推广风云榜
        $month_popularize = $this->Borrow_model->index_popularize(0); // 月推广
        $vdata['month_popularize'] = $month_popularize;

        $total_popularize = $this->Borrow_model->index_popularize(1); // 累计推广
        $vdata['total_popularize'] = $total_popularize;

        return $vdata;
    }

    function slinvest() {
        if ($this->session->userdata('zjy_user') == false) {//如果未登录就跳到登录页面
            $this->js->alert('请先登录');
            exit;
        }
        $id = intval($this->input->post("id"));
        $account = intval($this->input->post("account"));
        $timeLimit = intval($this->input->post("time_limit"));
        $paypassword = $this->input->post("paypassword");

        $user = $this->session->userdata('zjy_user');
        $this->load->model('User_model');
        $this->load->model('Yjb_model');
        $this->load->model('Account_model');


        $yjb = $this->Yjb_model->get_by_id($id);
        if (!$yjb) {
            $this->js->alert('数据错误');
            exit;
        }

        $pay_result = $this->User_model->check_paypassword($user['user_id'], $paypassword);
        if (!$pay_result) {
            $this->js->alert('支付密码不正确');
            exit;
        }

        if (!$this->myformcheck->IsDouble($account)) {
            $this->js->alert('投标金额不正确');
            exit;
        }
        if ((time() - $yjb['verify_time']) > ($yjb['valid_time'] * 3600 * 24)) {
            $this->js->alert('此标已过期');
            exit;
        }
        if ($yjb['account'] <= $yjb['account_yes']) {
            $this->js->alert('此标已满');
            exit;
        }

        if ($yjb['lowest_account'] > $account) {
            $this->js->alert('最低投标金额为' . $yjb['lowest_account']);
            exit;
        }


        if ($account % $yjb['one_account'] > 0) {
            $this->js->alert("必须为" . $yjb['one_account'] . "的倍数");
            exit;
        }
        if (($yjb['most_account'] > 0) && ($account > $yjb['most_account'])) {
            $this->js->alert('投标金额超过最大投标金额');
            exit;
        }

        if ($yjb['user_id'] == $user['user_id']) {
            $this->js->alert('不能投自己的标');
            exit;
        }
        $money = $account;
        if ($yjb['account'] - $yjb['account_yes'] < $account) {
            $account = $yjb['account'] - $yjb['account_yes'];
        }
        $user_account = $this->Account_model->get_account($user['user_id']);
        if ($account <= 0) {
            $this->js->alert('无效的金额');
            exit;
        }
        if ($user_account['use_money'] < $account) {
            $this->js->alert('您的可用金额不足，请先充值');
            exit;
        }

        //体验金检验
        $expMoney = $user_account['exp_money_12'] + $user_account['exp_money_24'];
        if ($user_account['use_money'] - $account < $expMoney) {
            $this->js->alert('体验金只能用于投资相应标种');
            exit;
        }

        /* $data['id'] 		= $id;
          $data['account'] 	= $account;
          $data['ip'] 		= $this->input->ip_address();
          $data['user_id'] 	= $user['user_id'];
          $data['borrow_id'] 	= $id;
          $data['borrow_user_id'] = $borrow_obj['user_id']; */

        $aprList = json_decode($yjb['apr_list'], true);
        $apr = $award = 0;
        foreach ($aprList as $val) {
            if ($timeLimit == $val['time_limit']) {
                $apr = $val['apr'];
                $award = $val['award'];
            }
        }
        //暂时先不考虑奖励
        $data['user_id'] = $user['user_id'];
        $data['fstatus'] = 1;
        $data['yjb_id'] = $id;
        $data['money'] = $money;
        $data['account'] = $account;
        $data['time_limit_day'] = $timeLimit;
        $data['apr'] = $apr;
        $data['add_time'] = time();
        $data['addip'] = $this->js->get_ip();
        $res = $this->Yjb_model->invest($data);

        if ($res) {
            $this->js->alert('投标成功');
            $this->js->go('/borrow/slobj/' . $id . '.html');
            exit;
        } else {
            $this->js->alert('投标失败');
            exit;
        }
    }

    function slobj($id = 0) {
        $id = intval($id);
        $user = $this->session->userdata('zjy_user');

        if (!isset($user['user_id']) || !$user['user_id']) {
            $this->js->alert("请先登录");
            $this->js->go('/login.html');
        }

        $this->load->model('Account_model');
        $this->load->model('Yjb_model');

        $yjb = $this->Yjb_model->get_by_id($id);
        if (!$yjb || !in_array($yjb['fstatus'], array(2, 3, 4))) {
            $this->js->alert('该借款标不存在');
            $this->js->go('/');
        }
        $vdata['yjb'] = $yjb;


        $user_account = array();
        if ($user == null) {
            $user_account['total'] = 0;
            $user_account['use_money'] = 0;
        } else {
            $user_account = $this->Account_model->get_account($user['user_id']);
            if ($user_account == false) {
                $user_account['total'] = 0;
                $user_account['use_money'] = 0;
            }
        }
        $vdata['user_account'] = $user_account;
        $where = array(
            'yjb_id' => $id
        );
        $tender_list = $this->Yjb_model->tender_list($where, true);
        $vdata['tender_list'] = $tender_list;
        //用户信息
        //$user_id = $borrow_obj['user_id'];
        //$user_obj = $this->User_model->get_by_uid($user_id);
        //$vdata['borrow'] = $borrow_obj;
        //$vdata['user_obj'] = $user_obj;
        //$this->load->model('Attestation_type_model');
        //$vdata['attestation_type_list'] = $this->Attestation_type_model->get_id_names();

        $vdata['title'] = $yjb['title'] . ' - ' . CON_KEYWORDS;
        $this->load->view('borrow/slobj', $vdata);
    }

    function slview() {
        $user = $this->session->userdata('zjy_user'); //获取用户session信息
        if ($user == null) {//如果未登录就跳到登录页面
            header('Location: /login.html');
        }
        $this->load->model('User_model');
        $this->load->model('Borrow_model');
        $user_obj = $this->User_model->get_all_by_id($user['user_id']);

        if ($user_obj['real_status'] != 1) {
            $this->js->alert("请先实名认证");
            $this->js->go("/user/realname");
        }
        if ($user_obj['email_status'] != 1) {
            $this->js->alert("请先Email认证");
            $this->js->go("/user/realname/index.html");
        }
        if ($user_obj['phone_status'] != 1) {
            $this->js->alert("请先手机认证");
            $this->js->go("/user/realname/index.html");
        }

//		//获取标属性信息
//		$vdata['borrow_time_limit'] 		= $this->Borrow_model->arrays('borrow_time_limit');//借款期限
//		$vdata['borrow_day_time_limit'] 	= $this->Borrow_model->arrays('borrow_day_time_limit');//借款期限
//		$vdata['borrow_use'] 				= $this->Borrow_model->arrays('borrow_use');//借款用途
//		$vdata['borrow_style'] 				= $this->Borrow_model->arrays('borrow_style');//还款方式
//		$vdata['borrow_lowest_account'] 	= $this->Borrow_model->arrays('borrow_lowest_account');//最低投标金额
//		$vdata['borrow_most_account'] 		= $this->Borrow_model->arrays('borrow_most_account');//最多投标总额
//		$vdata['borrow_valid_time'] 		= $this->Borrow_model->arrays('borrow_valid_time');//有效时间
//		$vdata['ftype'] 					= $ftype;
//		$vdata['fastid'] 					= $fastid;
        $vdata['title'] = "我要贷款" . ' - ' . CON_KEYWORDS;
        $this->load->view('borrow/slview', $vdata);
    }

    function sladd() {
        $ret = array(
            'msg' => '',
            'url' => '',
        );
        if ($this->session->userdata('zjy_user') == false) {//如果未登录就跳到登录页面
            $this->js->alert('请先登录');
            $this->js->go('/login.html');
        }
        $user = $this->session->userdata('zjy_user');

        $timeLimitArr = $this->input->post('time_limit');
        if (empty($timeLimitArr)) {
            $this->js->alert('请选择期限');
            exit;
        }

        //自动审核时间 ----start
        $auto_verify_time_post = $this->input->post("auto_verify_time");
        $min = date('i', strtotime($auto_verify_time_post));
        if ($min % 10 == 0) {
            $auto_verify_time = strtotime($auto_verify_time_post);
        } else {
            $m = round($min / 10) * 10;
            $new_time = date('Y-m-d H', strtotime($auto_verify_time_post));
            $auto_verify_time = strtotime($new_time . ':' . $m);
        }

        if ($auto_verify_time < time()) {
            $this->js->alert('自动审核时间不能小于发标时间');
            exit;
        }
        //自动审核时间 ----end

        $aprList = array();
        foreach ($timeLimitArr as $timeLimit) {
            if (!in_array($timeLimit, array(7, 15, 20, 30))) {
                $this->js->alert('期限错误');
                exit;
            }
            $tmpApr = round($this->input->post('apr' . $timeLimit), 2);
            $tmpAward = round($this->input->post('award' . $timeLimit), 2);
            if ($tmpApr <= 0 || $tmpApr > 24) {
                $this->js->alert('请填写有效利率');
                exit;
            }

            $aprList[] = array(
                'time_limit' => $timeLimit,
                'apr' => $tmpApr,
                'award' => $tmpAward
            );
        }
        $data['fstatus'] = 1; //[1未审核,2审核通过招标中,3已满标,4已还完,5取消]
        $data['apr_list'] = json_encode($aprList);
        $data['account'] = round($this->input->post("account"), 2);
        $data['lowest_account'] = round($this->input->post("lowest_account"), 2);
        $data['most_account'] = round($this->input->post("most_account"), 2);
        $data['one_account'] = round($this->input->post("one_account"), 2);
        $data['valid_time'] = intval($this->input->post("valid_time"));
        $data['index_title'] = trim($this->input->post('index_title'));
        $data['title'] = trim($this->input->post('title'));
        $data['content'] = $this->input->post("content");
        $data['add_time'] = time();
        $data['addip'] = $this->input->ip_address();
        $data['user_id'] = $user['user_id'];

        $data['auto_verify_time'] = $auto_verify_time;
        $data['is_check'] = 0;



        //验证
        if ($data['account'] < 1000 || $data['account'] > 100000000) {
            $this->js->alert('金额必须大于1000且小于1亿');
            exit;
        }
        if ($data['title'] == '') {
            $this->js->alert('标题不能为空');
            exit;
        }
        if ($data['content'] == '') {
            $this->js->alert('内容不能为空');
            exit;
        }

        $this->load->model('Yjb_model');

        $borrow_id = $this->Yjb_model->add($data);
        if ($borrow_id) {
            $this->js->alert('发标成功');
            $this->js->go('/borrow/slview.html');
            exit;
        } else {
            $this->js->alert('发标失败，请与管理员联系');
            exit;
        }
    }

    /**
     * 发标
     * @param $ftype 标类型
     * @param $fastid 抵押标信息
     */
    function publish($ftype = 0, $fastid = 0) {
        $user = $this->session->userdata('zjy_user'); //获取用户session信息
        //屏蔽除信用标外的其他标种
        /*
          if ($ftype != '1' && $ftype != 'index') {
          $this->js->go("/404");
          }
         *
         */

        if ($ftype != 0 && $ftype > 7) {
            $this->js->alert("借款标类型不正确");
            $this->js->go("/borrow/publish/index.html");
        }
        if ($user == null) {//如果未登录就跳到登录页面
            header('Location: /login.html');
        }
        $this->load->model('User_model');
        $this->load->model('Borrow_model');
        $user_obj = $this->User_model->get_all_by_id($user['user_id']);
        if (@$user_obj['real_status'] != 1) {
            $this->js->alert("请先实名认证");
            $this->js->go("/user/realname/index.html");
        }
        if ($user_obj['email_status'] == 0) {
            $this->js->alert("请先Email认证");
            $this->js->go("/user/email/index.html");
        }
        if ($user_obj['phone_status'] == 0) {
            $this->js->alert("请先手机认证");
            $this->js->go("/user/phone/index.html");
        }

        $vdata['tab'] = 'borrow';
        $vdata['active'] = "borrow";

        if ($ftype == 0) {//如果没有标类型，就去选择标类型
            $vdata['title'] = "我要贷款" . ' - ' . CON_KEYWORDS;
            $this->load->view('/borrow/borrow_type', $vdata);
            return;
        }

        if ($ftype == 2 && $fastid == 0) {//如果是抵押标，则需要去填写抵押信息
            $vdata['ftype'] = $ftype;
            $vdata['borrow_fast_yongtu'] = $this->Borrow_model->arrays('borrow_fast_yongtu'); //用途
            $vdata['borrow_fast_mortgage'] = $this->Borrow_model->arrays('borrow_fast_mortgage'); //是否有抵押
            $vdata['borrow_fast_diya'] = $this->Borrow_model->arrays('borrow_fast_diya'); //抵押物
            $vdata['borrow_fast_ddlage'] = $this->Borrow_model->arrays('borrow_fast_ddlage'); //年龄
            $vdata['borrow_fast_ddloccupation'] = $this->Borrow_model->arrays('borrow_fast_ddloccupation'); //职位
            $vdata['borrow_fast_ddlturnover'] = $this->Borrow_model->arrays('borrow_fast_ddlturnover'); //收入
            $vdata['borrow_fast_ddlindustry'] = $this->Borrow_model->arrays('borrow_fast_ddlindustry'); //行业
            $vdata['borrow_fast_ddlturnover'] = $this->Borrow_model->arrays('borrow_fast_ddlturnover'); //营业额
            $vdata['borrow_fast_ddlstaff'] = $this->Borrow_model->arrays('borrow_fast_ddlstaff'); //规模
            $vdata['borrow_fast_sex'] = $this->Borrow_model->arrays('borrow_fast_sex'); //性别
            $vdata['title'] = "我要贷款" . ' - ' . CON_KEYWORDS;
            $this->load->view('borrow/borrow_publish_fast', $vdata);
            return;
        }

        //获取标属性信息
        $vdata['borrow_time_limit'] = $this->Borrow_model->arrays('borrow_time_limit'); //借款期限
        $vdata['borrow_day_time_limit'] = $this->Borrow_model->arrays('borrow_day_time_limit'); //借款期限
        $vdata['borrow_use'] = $this->Borrow_model->arrays('borrow_use'); //借款用途
        $vdata['borrow_style'] = $this->Borrow_model->arrays('borrow_style'); //还款方式
        $vdata['borrow_lowest_account'] = $this->Borrow_model->arrays('borrow_lowest_account'); //最低投标金额
        $vdata['borrow_most_account'] = $this->Borrow_model->arrays('borrow_most_account'); //最多投标总额
        $vdata['borrow_valid_time'] = $this->Borrow_model->arrays('borrow_valid_time'); //有效时间
        $vdata['ftype'] = $ftype;
        $vdata['fastid'] = $fastid;
        $vdata['title'] = "我要贷款" . ' - ' . CON_KEYWORDS;

        if ($ftype == 7) {
            $vdata['guarantee_list'] = $this->Borrow_model->get_guarantee_borrow_list();
        }
        $vdata['borrow_arr'] = $this->Borrow_model->arrays('borrow_type1'); //借款期限

        $vdata['net_amount'] = self::net_value($user['user_id']);
        $vdata['active'] = "borrow";
        $this->load->view('borrow/borrow_publish', $vdata);
    }

    /**
     * 添加抵押标的信息
     */
    function fast_add() {
        $ret = array(
            'msg' => '',
            'url' => '',
        );
        if ($this->session->userdata('zjy_user') == false) {//如果未登录就跳到登录页面
            $ret['msg'] = '请先登录';
            $ret['url'] = '/login.html';
            echo json_encode($ret);
            exit;
        }
        $yongtu = $this->input->post("yongtu");
        $mortgage = $this->input->post("mortgage");
        $diya = $this->input->post("diya");
        $ddlage = $this->input->post("ddlage");
        $ddloccupation = $this->input->post("ddloccupation");
        $ddlincome = $this->input->post("ddlincome");
        $ddlindustry = $this->input->post("ddlindustry");
        $ddlturnover = $this->input->post("ddlturnover");
        $ddlstaff = $this->input->post("ddlstaff");
        $sex = $this->input->post("sex");
        $txtcontact = $this->input->post("txtcontact");
        $txttelephone = $this->input->post("txttelephone");
        $txtremark = $this->input->post("txtremark");

        $fdata['yongtu'] = $yongtu;
        $fdata['mortgage'] = $mortgage;
        $fdata['diya'] = $diya;
        $fdata['ddlage'] = $ddlage;
        $fdata['ddloccupation'] = $ddloccupation;
        $fdata['ddlincome'] = $ddlincome;
        $fdata['ddlindustry'] = $ddlindustry;
        $fdata['ddlturnover'] = $ddlturnover;
        $fdata['ddlstaff'] = $ddlstaff;
        $fdata['sex'] = $sex;
        $fdata['txtcontact'] = $txtcontact;
        $fdata['txttelephone'] = $txttelephone;
        $fdata['txtremark'] = $txtremark;
        $user = $this->session->userdata('zjy_user');
        $fdata['user_id'] = $user['user_id'];

        $this->load->model('Borrow_model');
        $fast_id = $this->Borrow_model->add_fast($fdata);

        $ret = array(
            'msg' => '',
            'url' => "/borrow/publish/2/$fast_id",
        );
        echo json_encode($ret);
        exit;
    }

    /**
     * 发标
     */
    function publish_add() {
        $ret = array(
            'msg' => '',
            'url' => '',
        );
        if ($this->session->userdata('zjy_user') == false) {//如果未登录就跳到登录页面
            $ret['msg'] = '请先登录';
            $ret['url'] = '/login.html';
            echo json_encode($ret);
            exit;
        }
        $user = $this->session->userdata('zjy_user');
        $fastid = $this->input->post("fastid");
        $ftype = $this->input->post("ftype");
        $fuse = $this->input->post("fuse");
        $time_limit = $this->input->post("time_limit") ? $this->input->post("time_limit") : 1;
        $is_day = $this->input->post("is_day");
        if ($ftype == 3) {
            $is_day = 1;
        }
        $time_limit_day = 0;
        if ($is_day == 1) {
            $time_limit_day = $this->input->post("time_limit_day");
        }
        $lz_times = $this->input->post("lz_times") ? $this->input->post("lz_times") : 0;
        $style = $this->input->post("style");
        $account = $this->input->post("account");
        $apr = $this->input->post("apr");
        $is_dxb = $this->input->post("is_dxb");
        $dxb_pwd = $this->input->post("dxb_pwd");
        $lowest_account = $this->input->post("lowest_account");
        $most_account = $this->input->post("most_account");
        $valid_time = $this->input->post("valid_time");
        $award = $this->input->post("award");
        $funds = $this->input->post("funds") ? $this->input->post("funds") : 0;
        $open_account = $this->input->post("open_account");
        $open_borrow = $this->input->post("open_borrow");
        $open_tender = $this->input->post("open_tender");
        $open_credit = $this->input->post("open_credit");
        $open_attestation = $this->input->post("open_attestation");
        $title = $this->input->post("title");
        $content = $this->input->post("content");
        $repay_from = $this->input->post("repay_from");
        $risk_manage = $this->input->post("risk_manage");
        $publish_remark = $this->input->post("publish_remark");
        $summary = $this->input->post("summary");
        $business = $this->input->post("business");
        $is_kjb = $this->input->post("is_kjb");
        $title_img = intval($this->input->post("title_img"));
        $cltroGoods = $this->input->post('cltroGoods');

        $project_number = $this->input->post("project_number");
        $guarantee_id = intval($this->input->post("guarantee_id"));

        $title_img = $title_img ? $title_img : 1;

        //自动审核时间 ----start
        $auto_verify_time_post = $this->input->post("auto_verify_time");
        $auto_verify_time = 0;
        if ($auto_verify_time_post) {
            $min = date('i', strtotime($auto_verify_time_post));
            if ($min % 10 == 0) {
                $auto_verify_time = strtotime($auto_verify_time_post);
            } else {
                $m = round($min / 10) * 10;
                $new_time = date('Y-m-d H', strtotime($auto_verify_time_post));
                $auto_verify_time = strtotime($new_time . ':' . $m);
            }
        }

        //自动审核时间 ----end

        //预设标开放时间
        $open_time = $this->input->post('open_time');
        if(strtotime($open_time)<time()){
            $ret['msg'] = "开放购买时间不能早于发标时间";
        }

        $this->load->model('Borrow_model');
        $this->load->model('Account_model');
        $this->load->model('User_amount_model');
        //验证
        if ($account < 500 || $account > 10000000) {
            $ret['msg'] = '金额必须大于500且小于1000w';
        }
        if ($apr <= 0 || $apr > 24) {
            $ret['msg'] = '年利率必须在0%-24%之间';
        }
        if($ftype == 3){ //净值标利息：必须在5%-18%之间
            if($apr<=5 || $apr>18){
                $ret['msg'] = '净值标年利率必须在5%-18%之间';
            }
        }
        if ($is_dxb == 1) {
            if ($dxb_pwd == '') {
                $ret['msg'] = '请输入定向标密码';
            }
        }
        if ($award == 2) {
            if ($funds < 0) {
                $ret['msg'] = '请输入奖励比例';
            }
        }
        if ($title == '') {
            $ret['msg'] = '标题不能为空';
        }
        if ($content == '') {
            $ret['msg'] = '内容不能为空';
        }
        /* if($project_number == ''){
          $ret['msg'] = '项目编号不能为空';
          } */

        if ($auto_verify_time > 0 && $auto_verify_time < strtotime('today', time())) {
            $ret['msg'] = '发标日期不能小于当日';
        }

//        $borrow_count = $this->Borrow_model->get_borrow_count(array('where' => array('user_id' => $user['user_id'], 'fstatus' => 1)));
//        if ($borrow_count > 0) {
//            $ret['msg'] = "您还有正在招标中的借款。";
//        }
        $user_account = $this->Account_model->get_account($user['user_id']);
        if ($ftype == 3) {//如果是净值标，则需要检查净值额度 (代收+可用-待还)*0.8
            $tmpMoney = $this->Borrow_model->no_repayment_borrow_3($user['user_id']);
            $money = ($user_account['collection'] + $user_account['use_money'] - $tmpMoney) * CON_BORROW_JIN_CREDIT;
            if (($user_account['collection'] + $user_account['use_money'] - $tmpMoney) * CON_BORROW_JIN_CREDIT < $account) {
                $ret['msg'] = $money;
            }
            $ret['msg'] = $money;
//            echo $user_account['use_money'];
        }
        if ($ftype == 5) {
            if ($user_account['use_money'] < ($apr * $account / (100 * 12))) {
                $ret['msg'] = "对不起，可用余额不足以支付利息，请充值！";
            }
        }
//        if ($ftype != 3 && $ftype != 5) {//如果是净值标或者秒标就不用额度
//            $user_amount = $this->User_amount_model->get_one($user['user_id']);
//            if ($user_amount['credit_use'] < $account) {
//                $ret['msg'] = "借款额度不足，请先申请额度。";
//            }
//        }

        if ($ret['msg']) {
            echo json_encode($ret);
            exit;
        }

        $idata['time_limit'] = $time_limit;
        $idata['style'] = $style;
        $idata['account'] = $account;
        $idata['apr'] = $apr;
        $idata['is_day'] = $is_day;
        $idata['time_limit_day'] = $time_limit_day;
        $idata['type'] = "all";
        $interest_result = equal_interest($idata);
        $data['repayment_account'] = $interest_result['repayment_account'];
        $data['monthly_repayment'] = $interest_result['monthly_repayment'];
        if ($is_day == 1 && $time_limit == 1) {
            $data['monthly_repayment'] = $interest_result['repayment_account'];
        }
        $data['ftype'] = $ftype;
        $data['fuse'] = $fuse;
        $data['time_limit'] = $time_limit;
        $data['is_day'] = $is_day;
        $data['time_limit_day'] = $time_limit_day;
        $data['style'] = $style;
        $data['lz_times'] = $lz_times;
        $data['account'] = $account;
        $data['apr'] = $apr;
        $data['is_dxb'] = $is_dxb;
        $data['dxb_pwd'] = $dxb_pwd;
        $data['lowest_account'] = $lowest_account;
        $data['most_account'] = $most_account;
        $data['valid_time'] = $valid_time;
        $data['award'] = $award;
        $data['funds'] = $funds;
        $data['open_account'] = $open_account;
        $data['open_borrow'] = $open_borrow;
        $data['open_tender'] = $open_tender;
        $data['open_credit'] = $open_credit;
        $data['open_attestation'] = $open_attestation;
        $data['title'] = $title;
        $data['content'] = $content;
        $data['repay_from'] = $repay_from;
        $data['risk_manage'] = $risk_manage;
        $data['publish_remark'] = $publish_remark;
        $data['summary'] = $summary;
        $data['business'] = $business;
        $data['add_time'] = time();
        $data['open_time'] = $open_time;
        $data['addip'] = $this->input->ip_address();
        $data['user_id'] = $user['user_id'];
        $data['is_kjb'] = $is_kjb;

        $data['auto_verify_time'] = $auto_verify_time;
        $data['guarantee_id'] = $guarantee_id;
        $data['project_number'] = $project_number;
        $data['cltroGoods'] = $cltroGoods;
//        $data['thumbnail'] = $this->uploadPicture();
        $data['thumbnail'] = $this->input->post("borrow_img");
        if(empty($data['thumbnail'])){
            $ret['msg'] = "上传标图片失败。";
            echo json_encode($ret);
            exit();
        }
        $data['is_check'] = 0;
        $data['title_img'] = $title_img;

        $borrow_id = $this->Borrow_model->add($data);
        if ($borrow_id == 0) {
            $ret['msg'] = "发标失败，请联系管理员。";
            echo json_encode($ret);
            exit;
        }

        if ($ftype == 2) {
            $this->Borrow_model->update_fast($fastid, array('borrow_id' => $borrow_id));
        }
        $ret['url'] = '/userborrow/unpublish/index.html';
        echo json_encode($ret);
        exit;
    }

    public function uploadPicture(){
        if(!file_exists(BORROW_IMG)){
            mkdir(BORROW_IMG,0777);
        }
        $pic = "";
        if($_FILES['thumbnail']['name'] != '')
        {
            $pic = sha1($_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR'].time().rand());
            $tmpfn = $_FILES['thumbnail']['name'];
            $pt=strrpos($tmpfn, ".");
            $retval=substr($tmpfn, $pt+1, strlen($tmpfn) - $pt);
            $pic.=".".$retval;
            $upfile = FCPATH.trim(BORROW_IMG, '/')."/".$pic;
            if(is_uploaded_file($_FILES['thumbnail']['tmp_name']))
                if(move_uploaded_file($_FILES['thumbnail']['tmp_name'],$upfile));
        }
        echo $pic;
//        return $pic;
    }



    /**
     * 标列表
     * @param $qtype 查询类型
     */
    function blist() {

        //搜索参数
        $postArr = array(
            'sftype' => intval($this->input->get('sftype')),
            'saccount' => intval($this->input->get('saccount')),
            'sapr' => intval($this->input->get('sapr')),
            'slimit' => intval($this->input->get('slimit')),
            'srate' => intval($this->input->get('srate')),
        );

        $vdata['active'] = "borrow";
        $vdata['postArr'] = $postArr;
        $this->load->model('Borrow_model');
        $this->load->model('User_model');
        $this->load->model('Credit_model');

        $per_page = $this->input->get('per_page') ? intval($this->input->get('per_page')) : 0;

        $data['where']['sftype'] = $postArr['sftype'];
        $data['where']['saccount'] = $postArr['saccount'];
        $data['where']['sapr'] = $postArr['sapr'];
        $data['where']['slimit'] = $postArr['slimit'];
        $data['where']['srate'] = $postArr['srate'];
        //$data['where']['qtype'] 		= $qtype;
        $data['where']['is_yjb'] = 0;
        $data['page_size'] = BORROW_LIST_PAGE_SIZE;
        $data['page_start'] = $per_page;
        $data['select'] = 1;
        $data['list'] = 0;
        $data['where']['keywords'] = $keywords;
        $data['where']['time_limit'] = $time_limit;
        $data['where']['ftype'] = $ftype;
        $retData = $this->Borrow_model->get_borrow_blist($data);
        $vdata['borrow_list'] = $retData['borrow_list'];

        //分页
        $this->load->library('pagination');
        $config['base_url'] = '/borrow/blist.html?sftype=' . $postArr['sftype'] . '&saccount=' . $postArr['saccount'] . '&sapr=' . $postArr['sapr'] . '&slimit=' . $postArr['slimit'] . '&srate=' . $postArr['srate'];
        $config['total_rows'] = $retData['borrow_count'];
        $config['per_page'] = $data['page_size'];
        $this->pagination->initialize($config);

        //获取用户资金信息
        if ($this->session->userdata('zjy_user') != null) {
            $user = $this->session->userdata('zjy_user');
            $this->load->model('Account_model');
            $vdata['user_account'] = $this->Account_model->get_account();
            $tuser_account = $this->User_model->get_by_uid($user['user_id']);
            if ($tuser_account == false) {
                $tuser_account['paypassword'] = "";
            } else {
                $vdata['user_paypassword'] = $tuser_account['paypassword'];
            }
        }

        $borrow_list = array();
        foreach ($vdata['borrow_list'] as $borrow) {
            if ($borrow['ftype'] != 6) {
                $user_id = $borrow['user_id'];
                $user_obj = $this->User_model->get_by_uid($user_id);
                $borrow['username'] = $user_obj['username'];
                $borrow['province'] = $user_obj['province'];
                $borrow['city'] = $user_obj['city'];
                $borrow['area'] = $user_obj['area'];
                $credit_obj = $this->Credit_model->get_row($user_id);
                $credit_obj['credit_value'] = isset($credit_obj) ? $credit_obj['credit_value'] : 0;
                $borrow['user_credit'] = $credit_obj['credit_value'];
                $borrow['user_credit_img'] = $this->Credit_model->get_pic($credit_obj['credit_value']);
                $borrow_list[] = $borrow;
            }
        }

        //获取地区信息
        $this->load->model('Area_model', 'area');
        $vdata['area_list'] = $this->area->get_list();
        $vdata['borrow_list'] = $borrow_list;	
        $vdata['borrow_type'] = $this->Borrow_model->arrays('borrow_type_search'); //标种
        $vdata['borrow_account'] = $this->Borrow_model->arrays('borrow_account'); // 投资金额
        $vdata['borrow_apr'] = $this->Borrow_model->arrays('borrow_apr'); // 年化利率
        $vdata['borrow_time_limit'] = $this->Borrow_model->arrays('borrow_time_limit_search'); //借款期限
        $vdata['borrow_style'] = $this->Borrow_model->arrays('borrow_style'); //还款方式
        $vdata['borrow_valid_time'] = $this->Borrow_model->arrays('borrow_valid_time'); //有效时间
        $vdata['borrow_rate'] = $this->Borrow_model->arrays('borrow_rate'); //进度

        $vdata['title'] = "我要投资" . ' - ' . CON_KEYWORDS;
        $vdata['tab'] = "tender";
        $this->load->view('borrow/borrow_list', $vdata);
    }

    /**
     * 标列表
     * @param $qtype 查询类型
     */
    function blate($qtype = 'late') {
        //搜索参数
        $per_page = $this->input->get('per_page') ? $this->input->get('per_page') : 0;
        $keywords = $this->input->get('keywords');
        $time_limit = $this->input->get('time_limit');
        $ftype = $this->input->get('ftype');

        $data['page_size'] = BORROW_LIST_PAGE_SIZE;
        $data['page_start'] = (int) $per_page;
        $this->load->model('Borrow_model');
        $vdata = $this->Borrow_model->get_late_list($data);

        //分页
        $this->load->library('pagination');
        $config['base_url'] = '/borrow/blate/index.html';
        $config['total_rows'] = $vdata['late_count'];
        $config['per_page'] = BORROW_LIST_PAGE_SIZE;
        $this->pagination->initialize($config);


        //获取地区信息
        $this->load->model('Area_model', 'area');
        $vdata['area_list'] = $this->area->get_list();
        $vdata['borrow_type'] = $this->Borrow_model->arrays('borrow_type'); //标种
        $vdata['borrow_time_limit'] = $this->Borrow_model->arrays('borrow_time_limit'); //借款期限
        $vdata['borrow_day_time_limit'] = $this->Borrow_model->arrays('borrow_day_time_limit'); //借款期限
        $vdata['borrow_style'] = $this->Borrow_model->arrays('borrow_style'); //还款方式
        $vdata['borrow_valid_time'] = $this->Borrow_model->arrays('borrow_valid_time'); //有效时间
        $vdata['qtype'] = "late";
        $vdata['time_limit'] = $time_limit;
        $vdata['ftype'] = $ftype;
        $vdata['keywords'] = $keywords;
        $vdata['title'] = "我要理财" . ' - ' . CON_KEYWORDS;
        $this->load->view('borrow/borrow_list', $vdata);
    }

    /**
     * 标详细信息
     * @param int $id 标ID
     */
    function obj($id) {
        $this->load->model('User_model');
        $this->load->model('User_info_model');
        $this->load->model('Area_model', 'area');
        $this->load->model('Account_model');
        $this->load->model('Borrow_model');
        $this->load->model('Credit_model');
        $this->load->model('User_amount_model');
        $this->load->model('Attestation_model');

        $user = $this->session->userdata('zjy_user');
        $data['select'] = 1;
        $borrow_obj = $this->Borrow_model->get_borrow_obj($id, $data);
        if ($borrow_obj['fstatus'] != 1 && $borrow_obj['fstatus'] != 3 && $borrow_obj['user_id'] != $user['user_id']) {
            $this->js->alert("您没有权限访问该借款标");
            $this->js->go("/borrow/blist/index.html");
        }
        if (!$borrow_obj) {
            $this->js->alert('该借款标不存在');
            $this->js->go('/');
        }

        $vdata = $this->borrow_common();

        $vdata['borrow_style'] = $this->Borrow_model->arrays('borrow_style'); //还款方式

        if ( (!isset($user['user_id']) || !$user['user_id']) && $borrow_obj['is_mjb'] == 1) {
            $this->js->alert("请先登录");
            $this->js->go('/login/index.html?obj='.$id);
        }

        $user_account = array();
        if ($user == null) {
            $user_account['total'] = 0;
            $user_account['use_money'] = 0;
        } else {
            $user_account = $this->Account_model->get_account($user['user_id']);
            if ($user_account == false) {
                $user_account['total'] = 0;
                $user_account['use_money'] = 0;
            }
        }
        $vdata['user_account'] = $user_account;
        $tuser_account = array();
        if ($user == null) {
            $tuser_account['paypassword'] = "";
        } else {
            $tuser_account = $this->User_model->get_by_uid($user['user_id']);
            if ($tuser_account == false) {
                $tuser_account['paypassword'] = "";
            }
        }
        $vdata['tuser_account'] = $tuser_account;
        $vdata['user_name_list'] = $this->User_model->get_name_list();
        $borrow_tender_list = $this->Borrow_model->get_borrow_tender(array('select' => 2, 'where' => array('borrow_id' => $id)));
        $borrow_tender_list1 = array();
        foreach ($borrow_tender_list as $tender) {
            $user_obj = $this->User_model->get_by_uid($tender['user_id']);
            $tender['username'] = $user_obj['username'];
            $borrow_tender_list1[] = $tender;
        }
        $vdata['borrow_tender_list'] = $borrow_tender_list1;


        //用户信息
        $user_id = $borrow_obj['user_id'];
        $user_obj = $this->User_model->get_by_uid($user_id);
        $credit_obj = $this->Credit_model->get_row($user_id);
        $borrow_obj['user_credit_img'] = '无';
        if (isset($credit_obj) && count($credit_obj) > 0) {
            $borrow_obj['user_credit'] = $credit_obj['credit_value'];
            $borrow_obj['user_credit_img'] = $this->Credit_model->get_pic($credit_obj['credit_value']);
        }
        $vdata['user_borrow_account'] = $this->Account_model->get_account($borrow_obj['user_id']);
        $vdata['user_borrow_account1'] = $this->Account_model->get_user_borrow_account_capital($borrow_obj['user_id']);
        $vdata['user_amount'] = $this->User_amount_model->get_one($borrow_obj['user_id']);
        $vdata['user_info'] = $this->User_info_model->get_by_uid($borrow_obj['user_id']);
        $vdata['user_borrow_num'] = $this->Borrow_model->user_borrow_total($borrow_obj['user_id']);
        $vdata['user_attestation'] = $this->Attestation_model->get_list(array('user_id' => $borrow_obj['user_id'], 'fstatus' => 1));
        //待还明细
        $user_borrow_repayment_list = $this->Borrow_model->get_repayment_list(array('where' => array('user_id' => $borrow_obj['user_id'], 'borrow_id' => $borrow_obj['id'], 'fstatus' => 0), 'select' => 1));
        $vdata['user_borrow_repayment'] = $user_borrow_repayment_list['repayment_list'];
        //待还流转标
        $vdata['user_lz_borrow_repayment'] = $this->Borrow_model->get_repayment_lz_borrow($borrow_obj['user_id']);

        //机构图片
        $guarantee_info = $this->Borrow_model->get_borrow_guarantee_obj($borrow_obj['guarantee_id']);
        if ($guarantee_info) {
            $this->load->model('Attestation_model', 'attestation');
            $attList = $this->attestation->get_list_guarantee($guarantee_info['id']);
            $vdata['attlist'] = $attList;
            $vdata['guarantee'] = $guarantee_info;
        }



        $vdata['borrow'] = $borrow_obj;
        $vdata['user_obj'] = $user_obj;
        $vdata['user_id'] = $user['user_id'];
        $this->load->model('Area_model', 'area');
        $vdata['area_list'] = $this->area->get_list();
        $this->load->model('User_vip_model');
        $vip = $this->User_vip_model->get_by_uid($borrow_obj['user_id']);
        if (isset($vip['vip_status']) && $vip['vip_status'] == 1) {
            $vdata['kefu'] = $this->User_model->get_by_uid($vip['kefu_userid']);
        }
        $this->load->model('Attestation_type_model');
        $vdata['attestation_type_list'] = $this->Attestation_type_model->get_id_names();
        $this->load->model('Linkage_model');
        $vdata['linkage'] = $this->Linkage_model->get_linkage_list();
        $vdata['title'] = $borrow_obj['title'] . ' - ' . CON_KEYWORDS;
		
		$vdata['borrow_type_html_arr'] = array(
			'1' => '信',
    		'2' => '抵',
    		'3' => '净',
    		'4' => '流',
    		'5' => '秒',
    		'7' => '担',
		);
        $vdata['borrow_type_img'] = $this->Borrow_model->arrays('borrow_type_img');
        $vdata['borrow_fuse_type'] = $this->Borrow_model->arrays('borrow_use');
        $vdata['active'] = "borrow";
        $this->load->view('borrow/borrow_obj', $vdata);
    }

    /**
     * 投标
     */
    function tender() {
        //接收参数
        if ($this->session->userdata('zjy_user') == false) {//如果未登录就跳到登录页面
            echo '请先登录';
            return;
        }
        $this->load->helper('captcha');
        /* if($this->input->post("captcha") != ''){
          if ($this->input->post("captcha") != $_SESSION['captcha']){
          echo '验证码不正确';
          return;
          }
          } */

        $id = $this->input->post("id");
        $account = $this->input->post("account");
        $paypassword = $this->input->post("paypassword");
        $dxb_pwd = $this->input->post("dxb_pwd") ? $this->input->post("dxb_pwd") : "";
        $user = $this->session->userdata('zjy_user');
        $this->load->model('User_model');
        $this->load->model('Borrow_model');
        $this->load->model('Account_model');
        //获取标信息
        $borrow_obj = $this->Borrow_model->get_borrow_obj($id, array('select' => 1));
        //判断是否为新手体验标
        if($borrow_obj['is_mjb'] == 1 ){
            $tenderList = $this->Borrow_model->borrow_tender_user_list(array('where'=>array('user_id'=>$user['user_id'],'no_del'=>1),'limit'=>'all'));
            $num = count($tenderList['tender_list']);
            if($num >0){
                echo "仅限新手投标";
                return;
            }
        }


        if ($borrow_obj['ftype'] == 4 || $borrow_obj['ftype'] == 6) {
            echo "入口错误";
            return;
        }
        //验证支付密码
        $pay_result = $this->User_model->check_paypassword($user['user_id'], $paypassword);
        //验证提交参数


        if ($borrow_obj['fstatus'] != 1) {
            echo "此标不能投";
            return;
        }
        if ((time() - $borrow_obj['verify_time']) > ($borrow_obj['valid_time'] * 3600 * 24)) {
            echo "此标已过期";
            return;
        }
        if ($borrow_obj['account'] <= $borrow_obj['account_yes']) {
            echo "此标已满";
            return;
        }
        if ($borrow_obj['lowest_account'] > $account) {
            echo "请输入正确的金额，最小投标金额为100元";
            return;
        }
        if (($borrow_obj['most_account'] > 0) && ($account > $borrow_obj['most_account'])) {
            echo "投标金额大于最大投标金额";
            return;
        }
        if ($borrow_obj['is_dxb'] == 1 && $dxb_pwd != $borrow_obj['dxb_pwd']) {
            echo "定向密码不正确";
            return;
        }

        if (($account % 100) != 0) {
            echo "必须是100的倍数";
            return;
        }

        if ($borrow_obj['user_id'] == $user['user_id']) {
            echo "不能投自己的标";
            return;
        }
        $user_tender_all = $this->Borrow_model->get_borrow_tender(array('where' => array('user_id' => $user['user_id'], 'borrow_id' => $id)));
        $user_tender_account = 0;
        foreach ($user_tender_all as $tender_obj) {
            $user_tender_account += $tender_obj['account'];
        }
        if (($borrow_obj['most_account'] > 0) && (($account + $user_tender_account) > $borrow_obj['most_account'])) {
            echo "投标金额大于最大投标金额";
            return;
        }
        if ($pay_result == '' || $pay_result == 0) {
            echo "支付密码不正确";
            return;
        }
        if (!$this->myformcheck->IsDouble($account)) {
            echo "投标金额不正确";
            return;
        }
        //封装参数
        $data['id'] = $id;
        $data['money'] = $account;
        $data['ip'] = $this->input->ip_address();
        $data['user_id'] = $user['user_id'];
        $data['borrow_user_id'] = $borrow_obj['user_id'];
        $data['borrow_id'] = $id;

        if ($borrow_obj['account'] - $borrow_obj['account_yes'] < $account) {
            $account = $borrow_obj['account'] - $borrow_obj['account_yes'];
        }

        $user_account = $this->Account_model->get_account($user['user_id']);
        if(($account > $user_account['use_money']+$user_account['reg_money']) && $borrow_obj['is_mjb'] == 1) {//如果是新手标,加上体验金
            echo "您的余额不足,请先充值";
            return;
        }
        if($account > $user_account['use_money'] && $borrow_obj['is_mjb'] == 0){
            echo "您的余额不足,请先充值";
            return;
        }
        if($borrow_obj['is_mjb'] == 1){
            if($account < 1000){
                echo "新手标投资要大于1000";
                return;
            }
        }

        if ($borrow_obj['ftype'] == 5 && $user_account['collection'] < SECOND_BORROW_LIMIT) {
            echo "您的待收不足".SECOND_BORROW_LIMIT.",不符合投标条件";
            return;
        }
        $account = round($account, 2);
        $account = max(0, $account);
//        $account = min($account, $user_account['use_money']);
        $data['account'] = $account;

        //注册体验金自动投标,优先使用体验金
        $use_reg_money = '';//剩余体验金
        $reg_money = '';//使用了多少体验金
        //是否使用体验金 0否 1是
        $is_exp = 0;
        if($user_account['reg_money'] > 0 && $borrow_obj['is_mjb'] == 1) {//体验金大于0且是新手标
            $is_exp = 1;
        }
        if ($is_exp) {
//            if ($borrow_obj['account'] - $borrow_obj['account_yes'] - $data['account'] >= 100) {
//                $data['money'] = $data['money'] + 100;
//                $data['account'] = $data['account'] + 100;
//                $this->Borrow_model->reg_money_use(array('user_id' => $user['user_id']));
//            }
            if($data['account'] > $user_account['reg_money']){//如果投的金额多于体验金，优先使用体验金
                $reg_money = $user_account['reg_money'];
                $data['account'] = $data['account'] - $user_account['reg_money'];
                $use_reg_money = 0;
            } elseif($data['account'] <= $user_account['reg_money']){//如果体验金多于投的金额，全部使用体验金
                $reg_money = $data['account'];
                $use_reg_money = $user_account['reg_money'] - $data['account'];
                $data['account'] = 0;
            }
        }

        //投标
        if($is_exp){
            $flag = $this->Borrow_model->borrow_tender($data,true,$reg_money);
        }else{
            $flag = $this->Borrow_model->borrow_tender($data);
        }
        if ($flag == 1) {
            //体验金操作
            if($is_exp){
                $this->db->query("update zjy_account set reg_money={$use_reg_money} where user_id={$user['user_id']}");
            }

            if ($borrow_obj['ftype'] == 5 || $borrow_obj['ftype'] == 3) {//是否秒标,或者净值标 是则执行自动复审操作
                $borrow_obj1 = $this->Borrow_model->get_borrow_obj($id, array('select' => 1));
                if ($borrow_obj1['account'] == $borrow_obj1['account_yes']) {//是否满标
                    //执行复审操作
                    $data['id'] = $id;
                    $data['ip'] = $this->input->ip_address();
                    $data["fstatus"] = 3;
                    $data["repayment_remark"] = "秒标自动复审";
                    $data["repayment_user"] = 1;
                    $flag = $this->Borrow_model->borrow_review_true($data);

                    if ($borrow_obj['ftype'] == 5) {//如果是秒标，则执行还款操作
                        $repayments = $this->Borrow_model->get_repayment_list(array('select' => 1, 'where' => array('borrow_id' => $id, 'fstatus' => 0)));
                        foreach ($repayments['repayment_list'] as $repayment) {
                            $data['repayment_id'] = $repayment['id'];
                            $data['user_id'] = $repayment['user_id'];
                            $data['ip'] = $this->input->ip_address();
                            $this->Borrow_model->repay($data);
                        }
                    }
                }
            }
            echo 1;
        } else {
            echo "投标失败";
        }
    }

    /**
     * 流转标投标
     */
    function lz_tender() {
        if ($this->session->userdata('zjy_user') == false) {//如果未登录就跳到登录页面
            echo '请先登录';
            return;
        }
        $this->load->helper('captcha');
        if ($this->input->post("captcha1") != '') {
            if ($this->input->post("captcha1") != $_SESSION['captcha']) {
                echo '验证码不正确';
                return;
            }
        }

        $id = $this->input->post("id");
        $account = intval($this->input->post("account"));
        $paypassword = $this->input->post("paypassword");
        $dxb_pwd = $this->input->post("dxb_pwd") ? $this->input->post("dxb_pwd") : "";
        $user = $this->session->userdata('zjy_user');
        $this->load->model('User_model');
        $this->load->model('Borrow_model');
        $this->load->model('Account_model');
        $borrow_obj = $this->Borrow_model->get_borrow_obj($id, array('select' => 1));
        if ($borrow_obj['ftype'] != 4) {
            echo "入口错误";
            return;
        }
        $pay_result = $this->User_model->check_paypassword($user['user_id'], $paypassword);
        if ($pay_result == '' || $pay_result == 0) {
            echo "支付密码不正确";
            return;
        }
        /* if(!$this->myformcheck->isNumber($money) || $money<1){
          echo "份额不正确";
          return;
          } */
        if (!$this->myformcheck->IsDouble($account)) {
            echo "投标金额不正确";
            return;
        }
        if (($account % 100) != 0) {
            echo "必须是100的倍数";
            return;
        }

        if ($borrow_obj['account'] <= $borrow_obj['account_yes']) {
            echo "此标已满";
            return;
        }
        if ($borrow_obj['user_id'] == $user['user_id']) {
            echo "不能投自己的标";
            return;
        }
        if ($borrow_obj['is_dxb'] == 1 && $dxb_pwd != $borrow_obj['dxb_pwd']) {
            echo "定向密码不正确";
            return;
        }
        //$account = $money*$borrow_obj['lowest_account'];
        $data['id'] = $id;
        $data['money'] = $account;
        $data['ip'] = $this->input->ip_address();
        $data['user_id'] = $user['user_id'];
        $data['borrow_id'] = $id;

        if ($borrow_obj['account'] - $borrow_obj['account_yes'] < $account) {
            $account = $borrow_obj['account'] - $borrow_obj['account_yes'];
        }
        $user_account = $this->Account_model->get_account($user['user_id']);
        if ($user_account['use_money'] < $account) {
            echo "您的余额不足，请先充值。";
            return;
        }
        if ($account <= 0) {
            echo "金额不正确";
            return;
        }
        //体验金检验
        $timeLimt = $borrow_obj['time_limit'];
        if ($timeLimt < 12) {
            $expMoney = $user_account['exp_money_12'] + $user_account['exp_money_24'];
            if ($user_account['use_money'] - $account < $expMoney) {
                echo "体验金只能用于投资相应标种";
                return;
            }
        } elseif ($timeLimt > 12) {
            $expMoney = $user_account['exp_money_12'];
            if ($user_account['use_money'] - $account < $expMoney) {
                echo "体验金只能用于投资相应标种";
                return;
            }
        }
        $account = max(0, $account);
        $account = min($account, $user_account['use_money']);
        $data['account'] = $account;

        $data['borrow_user_id'] = $borrow_obj['user_id'];

        //注册体验金自动投标
        if ($data['account'] >= 300 && $borrow_obj['time_limit'] >= 12 && $user_account['reg_money'] == 100) {
            if ($borrow_obj['account'] - $borrow_obj['account_yes'] - $data['account'] >= 100) {
                $data['money'] = $data['money'] + 100;
                $data['account'] = $data['account'] + 100;
                $this->Borrow_model->reg_money_use(array('user_id' => $user['user_id']));
            }
        }

        $flag = $this->Borrow_model->borrow_lz_tender($data);

        echo $flag;
    }

    /**
     * 标协议书 html
     * @param unknown_type $borrow_id
     */
    function protocol($borrow_id = '', $userId = 0) {
        $borrow_id = intval($borrow_id);
        if ($userId == 0){
            $user = $this->session->userdata('zjy_user');
            if (!$user){
                exit("请提供用户信息或您当前未登陆");
            }
            $userId = $user['user_id'];
        }

        if ($borrow_id > 0) {
            $this->load->model('Borrow_model');
            $this->load->model('User_model');
            $borrow_obj = $this->Borrow_model->get_borrow_obj($borrow_id, array('select' => 1));
            $tender_obj = $this->Borrow_model->get_borrow_tender(array('select' => 1, "where" => array('borrow_id' => $borrow_id, 'fstatus' => 1, 'user_id' => $userId)));
            $tenderMoney = 0;
            foreach ($tender_obj as $tender) {
                $user_obj = $this->User_model->get_by_uid($tender['user_id']);
                $tender['username'] = $user_obj['username'];
                $borrow_tender_list1[] = $tender;
            }

            $user_obj = $this->User_model->get_by_uid($borrow_obj['user_id']);
            $borrow_obj['username'] = $user_obj['username'];
            $vdata['borrow'] = $borrow_obj;
            $vdata['tender_list'] = $borrow_tender_list1;
            $vdata['title'] = $borrow_obj['title'] . ' - ' . CON_KEYWORDS;
            $this->load->view('/borrow/borrow_protocol', $vdata);
        }
    }

    /**
     * 标协议书pdf
     * @param unknown_type $borrow_id
     */
    function protocolview($borrow_id = '') {
        $borrow_id = intval($borrow_id);
        if ($borrow_id > 0) {
            $this->load->library('func');
            $html = $this->func->protocol_msg($borrow_id);
            $this->load->library('/MPDF56/mpdf');
            $this->mpdf->useAdobeCJK = true;
            $this->mpdf->SetAutoFont(AUTOFONT_ALL);
            $this->mpdf->SetDisplayMode('fullpage');
            $this->mpdf->showWatermarkText = true;
            $this->mpdf->SetAutoFont();

            $this->mpdf->showWatermarkText = true;
            $this->mpdf->SetAutoFont();

            $this->mpdf->WriteHTML($html);
            $this->mpdf->Output();
        }
    }

    /**
     * 流转标协议书 html
     * @param int $borrow_id
     * @param int $tender_id
     */
    function lz_protocol($borrow_id, $tender_id) {
        $borrow_id = intval($borrow_id);
        $tender_id = intval($tender_id);
        if ($borrow_id > 0 && $tender_id > 0) {
            $this->load->model('Borrow_model');
            $this->load->model('User_model');
            $borrow = $this->Borrow_model->get_borrow_obj($borrow_id, array('select' => 1));
            $user_obj = $this->User_model->get_by_uid($borrow['user_id']);
            $borrow['username'] = $user_obj['username'];

            $tender_obj = $this->Borrow_model->get_borrow_tender_obj($tender_id);
            $user_obj = $this->User_model->get_by_uid($tender_obj['user_id']);
            $tender_obj['username'] = $user_obj['username'];

            $eq['borrow_time'] = $tender_obj['add_time']; //@todo
            $eq['account'] = $tender_obj['account'];
            $eq['apr'] = $borrow['apr'];
            $eq['time_limit'] = $borrow['time_limit'];
            $eq['style'] = $borrow['style'];
            $eq['is_day'] = $borrow['is_day'];
            $eq['time_limit_day'] = $borrow['time_limit_day'];
            $eq['type'] = "all";
            $result = equal_interest($eq);
            $first_repayment_obj = $this->Borrow_model->first_repayment_time($borrow['user_id']);
            $result['repayment_end_time'] = $first_repayment_obj['repayment_time'];
			
			$vdata['borrow_fuse_type'] = $this->Borrow_model->arrays('borrow_use');

            $vdata['borrow'] = $borrow;
            $vdata['tender'] = $tender_obj;
            $vdata['interest'] = $result;
            $vdata['title'] = $borrow['title'] . ' - ' . CON_KEYWORDS;
            $this->load->view('/borrow/borrow_lz_protocol', $vdata);
        }
    }
	
	function lzp(){

		$vdata = array();
		$this->load->model('Borrow_model');
		$vdata['borrow_fuse_type'] = $this->Borrow_model->arrays('borrow_use');


		$this->load->view('/borrow/borrow_lz_protocol', $vdata);
	}

    /**
     * 流转标协议书pdf
     * @param int $borrow_id
     * @param int $tender_id
     */
    function lzprotocol($borrow_id, $tender_id) {
        $borrow_id = intval($borrow_id);
        $tender_id = intval($tender_id);
        if ($borrow_id > 0 && $tender_id > 0) {
            $this->load->library('func');
            $html = $this->func->protocol_msg($borrow_id, $tender_id);
            $this->load->library('/MPDF56/mpdf');
            $this->mpdf->useAdobeCJK = true;
            $this->mpdf->SetAutoFont(AUTOFONT_ALL);
            $this->mpdf->SetDisplayMode('fullpage');
            $this->mpdf->showWatermarkText = true;
            $this->mpdf->SetAutoFont();

            $this->mpdf->showWatermarkText = true;
            $this->mpdf->SetAutoFont();

            $this->mpdf->WriteHTML($html);
            $this->mpdf->Output();
        }
    }

    function sl_protocol($borrow_id, $tender_id) {
        $borrow_id = intval($borrow_id);
        $tender_id = intval($tender_id);
        $uid = intval($this->input->get('u'));
        $user = $this->session->userdata('zjy_user');
        $this->load->model('User_model');
        if (!$user) {
            $user = $this->User_model->get_by_uid($uid);
        }
        if (isset($user['user_id']) && $user['user_id'] > 0 && $borrow_id > 0 && $tender_id > 0) {
            $this->load->model('Yjb_model');
            $borrow = $this->Yjb_model->get_by_id($borrow_id);
            $user_obj = $this->User_model->get_by_uid($borrow['user_id']);
            $borrow['username'] = $user_obj['username'];
            $tender_obj = $this->Yjb_model->get_tender_by_id($tender_id);
            if ($user['user_id'] == $tender_obj['user_id']) {
                //$user_obj = $this->User_model->get_by_uid($tender_obj['user_id']);
                //$tender_user = $user_obj;
                //$repay_time = $tender_obj['add_time']+($borrow['time_limit_day']*60*60*24);
                //echo $repay_time;
                $vdata['borrow'] = $borrow;
                $vdata['tender'] = $tender_obj;
                //$vdata['interest'] 	= $result;
                //$vdata['tender_user'] = $tender_user;
                //$vdata['repay_time'] = $repay_time;

                $vdata['title'] = $borrow['title'] . ' - ' . CON_KEYWORDS;
                $this->load->view('/borrow/borrow_sl_protocol', $vdata);
            }
        }
    }

    function slprotocol($borrow_id, $tender_id) {
        $borrow_id = intval($borrow_id);
        $tender_id = intval($tender_id);
        $user = $this->session->userdata('zjy_user');
        $uid = isset($user['user_id']) ? $user['user_id'] : 0;
        if ($borrow_id > 0 && $tender_id > 0) {
            $this->load->library('func');
            $html = $this->func->yjb_pro_msg($borrow_id, $tender_id, $uid);
            $this->load->library('/MPDF56/mpdf');
            $this->mpdf->useAdobeCJK = true;
            $this->mpdf->SetAutoFont(AUTOFONT_ALL);
            $this->mpdf->SetDisplayMode('fullpage');
            $this->mpdf->showWatermarkText = true;
            $this->mpdf->SetAutoFont();

            $this->mpdf->showWatermarkText = true;
            $this->mpdf->SetAutoFont();

            $this->mpdf->WriteHTML($html);
            $this->mpdf->Output();
        }
    }

    /*     * ****************债权转让******************* */

    function transfer_list() {
        //债权转让列表
        $data['per_page'] = intval($this->input->get('per_page'));
        $data['page_size'] = 10; //YTZ_LIST_PAGE_SIZE;
        $this->load->model('Creditor_model');
        $ret = $this->Creditor_model->get_list($data);

        $this->load->library('pagination');
        $config['base_url'] = '/borrow/transfer_list.html?size=' . $data['page_size'];
        $config['total_rows'] = $ret['count'];
        $config['per_page'] = $data['page_size'];
        $this->pagination->initialize($config);

        $vdata['creditorList'] = $ret['list'];
        $vdata['title'] = '债权转让列表' . ' - ' . CON_KEYWORDS;
        $this->load->view('/borrow/transfer_list', $vdata);
    }

    /**
     * 债权项目详细
     * @param $id
     */
    function creditor($id = 0) {
        $id = intval($id);

        $this->load->model('Borrow_model');

        $vdata = $this->borrow_common();

        $this->load->model('Creditor_model');
        $obj = $this->Creditor_model->get_obj_by_id($id);

        $borrow_obj = $this->Borrow_model->get_borrow_obj($obj['borrow_id']);

        //剩余还款时间
        $time_limit = $borrow_obj['is_day']?'+'.$borrow_obj['time_limit'].'day':'+'.$borrow_obj['time_limit'].'month';
        $remaining_reapyment_time = (strtotime("+{$time_limit}",$borrow_obj['repayment_time'])) - time();

        /* if (!in_array($obj['fstatus'], array(2,3))){
          $this->js->alert('数据错误');
          exit;
          } */

        $this->load->model('Account_model');
        $user = $this->session->userdata('zjy_user');

//        if (!isset($user['user_id']) || !$user['user_id']) {
//            $this->js->alert("请先登录");
//            $this->js->go('/login.html');
//        }

        $user_account = array();
        if ($user == null) {
            $user_account['total'] = 0;
            $user_account['use_money'] = 0;
        } else {
            $user_account = $this->Account_model->get_account($user['user_id']);
            if ($user_account == false) {
                $user_account['total'] = 0;
                $user_account['use_money'] = 0;
            }
        }

        //账户表信息
        $vdata['user_account'] = $user_account;

        $this->load->model('User_model');

        $tuser_account = array();
        if ($user == null) {
            $tuser_account['paypassword'] = "";
        } else {
            $tuser_account = $this->User_model->get_by_uid($user['user_id']);
            if ($tuser_account == false) {
                $tuser_account['paypassword'] = "";
            }
        }
        //用户表信息
        $vdata['tuser_account'] = $tuser_account;


        $user_id = $obj['user_id'];
        $user_obj = $this->User_model->get_by_uid($user_id);

        $this->load->model('Credit_model');
        $credit_obj = $this->Credit_model->get_row($obj['user_id']);
        $borrow_obj['user_credit_img'] = '无';
        if (isset($credit_obj) && count($credit_obj) > 0) {
            $borrow_obj['user_credit'] = $credit_obj['credit_value'];
            $borrow_obj['user_credit_img'] = $this->Credit_model->get_pic($credit_obj['credit_value']);
        }

        $this->load->model('Attestation_model', 'attestation');
        $this->load->model('User_info_model');
        $vdata['user_info'] = $this->User_info_model->get_by_uid($borrow_obj['user_id']);
        $vdata['user_attestation'] = $this->attestation->get_list(array('user_id' => $borrow_obj['user_id'], 'fstatus' => 1));

        //机构图片
        $guarantee_info = $this->Borrow_model->get_borrow_guarantee_obj($borrow_obj['guarantee_id']);
        if ($guarantee_info) {
            $attList = $this->attestation->get_list_guarantee($guarantee_info['id']);
            $vdata['attlist'] = $attList;
            $vdata['guarantee'] = $guarantee_info;
        }



        $this->load->model('Attestation_type_model');
        $vdata['attestation_type_list'] = $this->Attestation_type_model->get_id_names();

        //项目评论
        $comments = $this->Borrow_model->get_borrow_comment_list(array('borrow_id' => $borrow_obj['id']), 0, 3);
        $vdata['succ_list'] = $comments['list'];


        $whereArr = array('tender_id' => $obj['tender_id'],
            'user_id' => $obj['user_id'],
            'borrow_id' => $obj['borrow_id'],
            'forder' => intval($borrow_obj['time_limit'] - 1),
        );

        //未还款的最后一条估计还款时间
        $obj['repay_time'] = $this->Creditor_model->get_creditor_collection_repay_time($whereArr);

        //剩余时间
        $remaining_time = $obj['verify_time']+86400*30*$obj['valid_time']-time();
        if($remaining_time > 0) {
            $obj['remaining_time_month'] = floor($remaining_time/(86400*30));
            $obj['remaining_time_day'] = floor($remaining_time%(86400*30)/86400);

        } else {
            $obj['remaining_time_month'] = 0;
            $obj['remaining_time_day'] = 0;
        }

        //预期收益
        $obj['expected_revenue'] = $obj['wait_interest']+$obj['account']-$obj['discount_account'];

        //转让标的年化收益
        $obj['creditor_apr'] = round($obj['expected_revenue']/$obj['discount_account']/($remaining_reapyment_time/(86400*30*12)),2)*100;

        //转让标信息
        $vdata['obj'] = $obj;

        //购买记录
        $buyers = $this->Creditor_model->get_buyers($id);
        $vdata['buyers'] = $buyers;

        $vdata['user_obj'] = $user_obj;

        //获得还款方式的名字
        $borrow_styles = $this->Borrow_model->arrays('borrow_style');
        $borrow_obj['style_name'] = $borrow_styles[$borrow_obj['style']];
        $vdata['borrow'] = $borrow_obj;

        $vdata['title'] = $obj['title'] . ' - ' . CON_KEYWORDS;
        $this->load->view('/borrow/borrow_creditor', $vdata);
    }

    /**
     * 转让
     */
    function creditor_transfer() {
        $this->load->model('User_model');
        $this->load->model('Account_model');
        $this->load->model('Creditor_model');

        $id = intval($this->input->get_post('id'));
        $money = $this->input->get_post('money');
        $paypassword = $this->input->get_post("paypassword");

        $obj = $this->Creditor_model->get_obj_by_id($id);

        if (!$obj) {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo '数据错误';
            exit;
        }

        if (!$this->myformcheck->IsDouble($money)) {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo '金额不合法';
            exit;
        }
        $money = round($money, 2);

        $user = $this->session->userdata('zjy_user');
        if (!$user || !isset($user['user_id'])) {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo '请先登录';
            exit;
        }
        $pay_result = $this->User_model->check_paypassword($user['user_id'], $paypassword);
        if (!$pay_result) {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo '支付密码不正确';
            exit;
        }

        if ((time() - $obj['verify_time']) > ($obj['valid_time'] * 3600 * 24)) {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo '此标已过期';
            exit;
        }

        if ($obj['user_id'] == $user['user_id']) {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo '不能购买自己的债权';
            exit;
        }

        if ($obj['discount_yes'] >= $obj['discount_account']) {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo '该债权已售完';
            exit;
        }

        if ($money < 100) {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo '最低购入金额100';
            exit;
        }

        if ($obj['discount_account'] - $obj['discount_yes'] < $money) {
            $money = $obj['discount_account'] - $obj['discount_yes'];
        }

        $user_account = $this->Account_model->get_account($user['user_id']);
        if ($money <= 0) {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo '无效的金额';
            exit;
        }

        $this->load->model('Accountlog_model', 'accountlog');
        $account_tyj = $this->accountlog->get_sum_type($user['user_id'], EXP_MONEY);
		$account_tyj_kc = $this->accountlog->get_sum_type($user['user_id'], EXP_MONEY_DEDUCT);
		$account_tyj = $account_tyj-$account_tyj_kc;

        if (($user_account['use_money'] - $account_tyj) < $money) {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo '您的可用金额不足，请先充值';
            exit;
        }

        /* //体验金检验
          $expMoney = $user_account['exp_money_12']+$user_account['exp_money_24'];
          if ($user_account['use_money']-$money<$expMoney){
          echo '体验金只能用于投资相应标种';
          exit;
          } */

        //$repay_account = 0;
        //取两位小数 不四舍五入
        //$repay_account = intval($obj['wait_account'] * ($money/$obj['discount_account']) *100)/100;
        //移到复审计算待收

        $data = array(
            'obj_id' => $id,
            'tender_id' => $obj['tender_id'],
            'fstatus' => 1,
            'user_id' => $user['user_id'],
            'discount_account' => $obj['discount_account'],
            'discount_buy' => $money,
            'repay_account' => 0, //待收金额
            'repay_yesaccount' => 0, //已收金额
            'add_time' => time(),
        );
//        $parastr = $id . '#' . $obj['tender_id'] . '#1#' . $user['user_id'] . '#' . $obj['discount_account'] . '#' . $money . '#0#0#';
//        $user = $this->User_model->get_by_uid($obj['user_id']);
//        self::loantransfer_creditor($id, $obj['tender_id'], $money, $obj['discount_account'], $user['mmm_id'], $parastr);
        $ret = $this->Creditor_model->creditor_transfer($data);
        echo $ret ? '购买成功' : '购买失败';
    }


    public function loantransfer($bmmm_id, $money, $borrowMoney, $borrow_id, $borrow_fee, $data) {
        $this->load->library('/mmm/Rsa', 'rsa');
        $this->load->library('/mmm/Common', 'common');
        $this->load->library('/mmm/LoanInfoBean', 'loaninfobean');
        $this->load->library('/mmm/LoanInfoSecondaryBean', 'loaninfosecondarybean');

        $userObj = $this->session->userdata('zjy_user');
        $this->load->model("User_model");
        $user = $this->User_model->get_by_uid($userObj['user_id']);
        $this->load->model("Account_model");
        $user_account = $this->Account_model->get_account($user['user_id']);

        $SecondaryJsonList = "";
        if ($borrow_fee > 0) {
            $bili = $borrow_fee / $borrowMoney;

            $secondary1 = new LoanInfoSecondaryBean(MONEYMOREMOREPID, $money * $bili, "借款管理费", "");
            $arrsecondary = array('0' => array("LoanInMoneymoremore" => $secondary1->LoanInMoneymoremore,
                    "Amount" => $secondary1->Amount,
                    "TransferName" => $secondary1->TransferName,
                    "Remark" => $secondary1->Remark));
            $SecondaryJsonList = json_encode($arrsecondary);
        }

    	if($user_account['exp_money'] == 0.00){
        	$invNo = MONEYMOREMOREPID . '#' . $borrow_id . '#' . date('YmdHis');
	        $ExchangeBatchNo = "";
	        $AdvanceBatchNo = "";
                //体验金管理费
                if ($borrow_fee > 0) {
                    $arrsecondary[0]['Amount'] = EXP_MONEY * $bili;
                    $SecondaryJsonList = json_encode($arrsecondary);
                }

	        $loaninfo1 = new LoanInfoBean(MONEYMOREMOREPID, $bmmm_id, $invNo, 'tp_' . $borrow_id, $ExchangeBatchNo, $AdvanceBatchNo, EXP_MONEY, $borrowMoney, "投标", $borrow_id . '=' . $invNo . '=' . EXP_MONEY.'=P', $SecondaryJsonList);
	        $arrloaninfo[] = array("LoanOutMoneymoremore" => $loaninfo1->LoanOutMoneymoremore,
	                "LoanInMoneymoremore" => $loaninfo1->LoanInMoneymoremore,
	                "OrderNo" => $loaninfo1->OrderNo,
	                "BatchNo" => $loaninfo1->BatchNo,
	                "ExchangeBatchNo" => $loaninfo1->ExchangeBatchNo,
	                "AdvanceBatchNo" => $loaninfo1->AdvanceBatchNo,
	                "Amount" => $loaninfo1->Amount,
	                "FullAmount" => $loaninfo1->FullAmount,
	                "TransferName" => $loaninfo1->TransferName,
	                "Remark" => $loaninfo1->Remark,
	                "SecondaryJsonList" => $loaninfo1->SecondaryJsonList);

	        ///////////////////////////////////////////////////////////////////////////////
	        $invNo = $user["user_id"] . '#' . $borrow_id . '#' . date('YmdHis');
	        $ExchangeBatchNo = "";
	        $AdvanceBatchNo = "";
                //体验金管理费
                if ($borrow_fee > 0) {
                    $arrsecondary[0]['Amount'] = ($money-EXP_MONEY) * $bili;
                    $SecondaryJsonList = json_encode($arrsecondary);
                }
	        $loaninfo1 = new LoanInfoBean($user['mmm_id'], $bmmm_id, $invNo, 't_' . $borrow_id, $ExchangeBatchNo, $AdvanceBatchNo, $money-EXP_MONEY, $borrowMoney, "投标", $borrow_id . '=' . $invNo . '=' . ($money-EXP_MONEY), $SecondaryJsonList);

	        $arrloaninfo[] = array("LoanOutMoneymoremore" => $loaninfo1->LoanOutMoneymoremore,
	                "LoanInMoneymoremore" => $loaninfo1->LoanInMoneymoremore,
	                "OrderNo" => $loaninfo1->OrderNo,
	                "BatchNo" => $loaninfo1->BatchNo,
	                "ExchangeBatchNo" => $loaninfo1->ExchangeBatchNo,
	                "AdvanceBatchNo" => $loaninfo1->AdvanceBatchNo,
	                "Amount" => $loaninfo1->Amount,
	                "FullAmount" => $loaninfo1->FullAmount,
	                "TransferName" => $loaninfo1->TransferName,
	                "Remark" => $loaninfo1->Remark,
	                "SecondaryJsonList" => $loaninfo1->SecondaryJsonList);
	        $LoanJsonList = json_encode($arrloaninfo);

        }else{
        	$invNo = $user["user_id"] . '#' . $borrow_id . '#' . date('YmdHis');
	        $ExchangeBatchNo = "";
	        $AdvanceBatchNo = "";
	        $loaninfo1 = new LoanInfoBean($user['mmm_id'], $bmmm_id, $invNo, 't_' . $borrow_id, $ExchangeBatchNo, $AdvanceBatchNo, $money, $borrowMoney, "投标", $borrow_id . '=' . $invNo . '=' . $money, $SecondaryJsonList);

	        $arrloaninfo = array('0' => array("LoanOutMoneymoremore" => $loaninfo1->LoanOutMoneymoremore,
	                "LoanInMoneymoremore" => $loaninfo1->LoanInMoneymoremore,
	                "OrderNo" => $loaninfo1->OrderNo,
	                "BatchNo" => $loaninfo1->BatchNo,
	                "ExchangeBatchNo" => $loaninfo1->ExchangeBatchNo,
	                "AdvanceBatchNo" => $loaninfo1->AdvanceBatchNo,
	                "Amount" => $loaninfo1->Amount,
	                "FullAmount" => $loaninfo1->FullAmount,
	                "TransferName" => $loaninfo1->TransferName,
	                "Remark" => $loaninfo1->Remark,
	                "SecondaryJsonList" => $loaninfo1->SecondaryJsonList),
	        );
	        $LoanJsonList = json_encode($arrloaninfo);
        }

        $PlatformMoneymoremore = MONEYMOREMOREPID;
        $TransferAction = "1";
        $Action = "1";
        $TransferType = "2";
        $NeedAudit = "";
        if ($this->common->getAntiState() == 0) {
            $RandomTimeStamp = "";
        } else if ($this->common->getAntiState() == 1) {
            $RandomTimeStamp = $this->common->getRandomTimeStamp();
        }
        $Remark1 = $invNo;
        $Remark2 = $data;
        $Remark3 = "";
        $ReturnURL = "http://" . $_SERVER["HTTP_HOST"] . "/borrow/transferreturn.html";
        $NotifyURL = "http://" . $_SERVER["HTTP_HOST"] . "/borrow/transfernotify.html";

        $dataStr = $LoanJsonList . $PlatformMoneymoremore . $TransferAction . $Action . $TransferType . $NeedAudit . $RandomTimeStamp . $Remark1 . $Remark2 . $Remark3 . $ReturnURL . $NotifyURL;
        if ($this->common->getAntiState() == 1) {
            $dataStr = strtoupper(md5($dataStr));
        }
        $SignInfo = $this->rsa->sign($dataStr);

        $LoanJsonList = urlencode($LoanJsonList);

        $officialAction = MONEYMOREMOREURL . "/loan/loan.action";

        echo "<form id=\"formu\" name=\"formu\" action=\"" . $officialAction . "\" method=\"post\">";
        echo "<input id=\"LoanJsonList\" name=\"LoanJsonList\" value=\"" . $LoanJsonList . "\" type=\"hidden\" />";
        echo "<input id=\"PlatformMoneymoremore\" name=\"PlatformMoneymoremore\" value=\"" . $PlatformMoneymoremore . "\" type=\"hidden\" />";
        echo "<input id=\"TransferAction\" name=\"TransferAction\" value=\"" . $TransferAction . "\" type=\"hidden\" />";
        echo "<input id=\"Action\" name=\"Action\" value=\"" . $Action . "\" type=\"hidden\" />";
        echo "<input id=\"TransferType\" name=\"TransferType\" value=\"" . $TransferType . "\" type=\"hidden\" />";
        echo "<input id=\"NeedAudit\" name=\"NeedAudit\" value=\"" . $NeedAudit . "\" type=\"hidden\" />";
        echo "<input id=\"RandomTimeStamp\" name=\"RandomTimeStamp\" value=\"" . $RandomTimeStamp . "\" type=\"hidden\" />";
        echo "<input id=\"Remark1\" name=\"Remark1\" value=\"" . $Remark1 . "\" type=\"hidden\" />";
        echo "<input id=\"Remark2\" name=\"Remark2\" value=\"" . $Remark2 . "\" type=\"hidden\" />";
        echo "<input id=\"Remark3\" name=\"Remark3\" value=\"" . $Remark3 . "\" type=\"hidden\" />";
        echo "<input id=\"ReturnURL\" name=\"ReturnURL\" value=\"" . $ReturnURL . "\" type=\"hidden\" />";
        echo "<input id=\"NotifyURL\" name=\"NotifyURL\" value=\"" . $NotifyURL . "\" type=\"hidden\" />";
        echo "<input id=\"SignInfo\" name=\"SignInfo\" value=\"" . $SignInfo . "\" type=\"hidden\" />";
        echo "<script language=\"javascript\">window.onload=function(){document.formu.submit();}</script>";
        echo "</form>";
    }

    public function transferreturn() {
        $this->load->library('/mmm/Rsa', 'rsa');
        $this->load->library('/mmm/Common', 'common');
        $this->load->library('/mmm/LoanInfoBean', 'loaninfobean');
        $this->load->library('/mmm/LoanInfoSecondaryBean', 'loaninfosecondarybean');

        $LoanJsonList = $_POST["LoanJsonList"];
        $LoanJsonList = urldecode($LoanJsonList);
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];

        $dataStr = $LoanJsonList . $PlatformMoneymoremore . $RandomTimeStamp . $Remark1 . $Remark2 . $Remark3 . $ResultCode;
        if ($this->common->getAntiState() == 1) {
            $dataStr = strtoupper(md5($dataStr));
        }
        $verifySignature = $this->rsa->verify($dataStr, $SignInfo);
        if ($ResultCode == 88) {
            $returnJson = json_decode(urldecode($LoanJsonList), true);
            $LoanNo = "";
            foreach ($returnJson as $jobj){
            	$LoanNo[] = $jobj['LoanNo'];
            }
            $loanstr = implode(",", $LoanNo);

            $paranmstr = explode("=", $Remark2);
            $data['id'] = $paranmstr[0];
            $data['money'] = $paranmstr[1];
            $data['ip'] = $paranmstr[2];
            $data['user_id'] = $paranmstr[3];
            $data['borrow_user_id'] = $paranmstr[4];
            $data['borrow_id'] = $paranmstr[5];
            $data['account'] = $paranmstr[6];
            $data['mmmloanno'] = $loanstr;
            $this->load->model('Borrow_model');
            $is_exp = count($returnJson) > 1 ? true : false;
            /*$this->Borrow_model->borrow_tender($data,$is_exp);
            $this->load->model("Account_model");
            $this->Account_model->updateexpmoney($paranmstr[3],array("exp_money"=>EXP_MONEY));*/
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo "<script>alert('操作成功');window.location.href='/borrow/obj/" . $data['borrow_id'] . "';</script>";
        } else {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo $Message;
        }
    }

    public function transfernotify() {
        $this->load->library('/mmm/Rsa', 'rsa');
        $this->load->library('/mmm/Common', 'common');
        $this->load->library('/mmm/LoanInfoBean', 'loaninfobean');
        $this->load->library('/mmm/LoanInfoSecondaryBean', 'loaninfosecondarybean');

        $LoanJsonList = $_POST["LoanJsonList"];
        $LoanJsonList = utf8_decode($LoanJsonList);
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];

        $dataStr = $LoanJsonList . $PlatformMoneymoremore . $RandomTimeStamp . $Remark1 . $Remark2 . $Remark3 . $ResultCode;
        if ($this->common->getAntiState() == 1) {
            $dataStr = strtoupper(md5($dataStr));
        }
        $verifySignature = $this->rsa->verify($dataStr, $SignInfo);
        if ($ResultCode == 88) {
            /*$fp = fopen("d:/ch/1touzi1.txt", "w");//文件被清空后再写入
			$flag=fwrite($fp,urldecode($LoanJsonList));
			fclose($fp);*/
            $returnJson = json_decode(urldecode($LoanJsonList), true);
            $LoanNo = "";
            foreach ($returnJson as $jobj){
            	$LoanNo[] = $jobj['LoanNo'];
            }
            $loanstr = implode(",", $LoanNo);

            $paranmstr = explode("=", $Remark2);
            $data['id'] = $paranmstr[0];
            $data['money'] = $paranmstr[1];
            $data['ip'] = $paranmstr[2];
            $data['user_id'] = $paranmstr[3];
            $data['borrow_user_id'] = $paranmstr[4];
            $data['borrow_id'] = $paranmstr[5];
            $data['account'] = $paranmstr[6];
            $data['mmmloanno'] = $loanstr;
            $this->load->model('Borrow_model');
            $is_exp = count($returnJson) > 1 ? true : false;
            $this->Borrow_model->borrow_tender($data,$is_exp);
            $this->load->model("Account_model");
            $this->Account_model->updateexpmoney($paranmstr[3],array("exp_money"=>EXP_MONEY));
            echo "SUCCESS";
        } else {
            echo "后台通知:" . $verifySignature;
            echo "<br>";
            echo "返回码:" . $ResultCode;
        }
    }

    function borrow_comment_synchronize() {
        $response_html = '';
        $borrow_id = intval($this->input->post("borrow_id"));
        $key = 'borrow_comment_key_' . $borrow_id;

        $this->load->model('Borrow_model');
        $succ_list = $this->mycache->get_array($key);
        if ($succ_list == false) {
            $vdata = $this->Borrow_model->get_borrow_comment_list(array('borrow_id' => $borrow_id), 0, 3);
            $succ_list = $vdata['list'];
        }


        if (is_array($succ_list) && count($succ_list) > 0) {
            if (count($succ_list) > 3) {
                $succ_list = array_slice($succ_list, 1, 3);
            }
            foreach ($succ_list as $temp) {
                $comment['comment'] = $temp;
                $response_html .= $this->load->view('borrow/borrow_comment_synchronize.php', $comment, true);
            }
        }
        echo $response_html;
        exit;
    }

    public function borrow_comment() {
        $user = $this->session->userdata('zjy_user'); //获取用户session信息
        if (isset($user['user_id']) && $user['user_id'] > 0) {

            $this->load->model('User_model');
            $this->load->model('Borrow_model');
            $user_id = intval($user['user_id']);

            $userobj = $this->User_model->get_username_by_id($user_id);

            $content = trim($this->input->post("content"));
            $borrow_id = intval($this->input->post("borrow_id"));
            $data = array('user_id' => $user_id,
                'content' => $content,
                'status' => 0,
                'borrow_id' => $borrow_id,
                'add_time' => time()
            );
            $res = $this->Borrow_model->borrow_comment_add($data);

            $data['username'] = $userobj['username'];
            $data['id'] = $res;
            $key = 'borrow_comment_key_' . $borrow_id;
            $comment_list = $this->mycache->get_array($key);
            array_unshift($comment_list, $data);
            $this->mycache->set_array($key, $comment_list);
            if ($res > 0) {
                echo 'ok';
            } else {
                echo 1;
            }
        } else {
            echo 2;
            exit;
        }
    }


    public function loantransfer_creditor($id, $tender_id, $money, $cMoney, $bmmm_id, $parastr) {
        $this->load->library('/mmm/Rsa', 'rsa');
        $this->load->library('/mmm/Common', 'common');
        $this->load->library('/mmm/LoanInfoBean', 'loaninfobean');
        $this->load->library('/mmm/LoanInfoSecondaryBean', 'loaninfosecondarybean');

        $userObj = $this->session->userdata('zjy_user');
        $this->load->model("User_model");
        $user = $this->User_model->get_by_uid($userObj['user_id']);

        $SecondaryJsonList = "";
        $invNo = $user["user_id"] . '#' . $id . '#' . date('YmdHis');
        $ExchangeBatchNo = "";
        $AdvanceBatchNo = "";
        $loaninfo1 = new LoanInfoBean($user['mmm_id'], $bmmm_id, $invNo, 'c_' . $id, $ExchangeBatchNo, $AdvanceBatchNo, $money, $cMoney, "债权转让", $id . '=' . $invNo . '=' . $money, $SecondaryJsonList);

        $arrloaninfo = array('0' => array("LoanOutMoneymoremore" => $loaninfo1->LoanOutMoneymoremore,
                "LoanInMoneymoremore" => $loaninfo1->LoanInMoneymoremore,
                "OrderNo" => $loaninfo1->OrderNo,
                "BatchNo" => $loaninfo1->BatchNo,
                "ExchangeBatchNo" => $loaninfo1->ExchangeBatchNo,
                "AdvanceBatchNo" => $loaninfo1->AdvanceBatchNo,
                "Amount" => $loaninfo1->Amount,
                "FullAmount" => $loaninfo1->FullAmount,
                "TransferName" => $loaninfo1->TransferName,
                "Remark" => $loaninfo1->Remark,
                "SecondaryJsonList" => $loaninfo1->SecondaryJsonList),
        );
        $LoanJsonList = json_encode($arrloaninfo);

        $PlatformMoneymoremore = MONEYMOREMOREPID;
        $TransferAction = "1";
        $Action = "1";
        $TransferType = "2";
        $NeedAudit = "";
        if ($this->common->getAntiState() == 0) {
            $RandomTimeStamp = "";
        } else if ($this->common->getAntiState() == 1) {
            $RandomTimeStamp = $this->common->getRandomTimeStamp();
        }
        $Remark1 = $invNo;
        $Remark2 = $parastr;
        $Remark3 = "";
        $ReturnURL = "http://" . $_SERVER["HTTP_HOST"] . "/borrow/transfercreditorreturn.html";
        $NotifyURL = "http://" . $_SERVER["HTTP_HOST"] . "/borrow/transfercreditornotify.html";

        $dataStr = $LoanJsonList . $PlatformMoneymoremore . $TransferAction . $Action . $TransferType . $NeedAudit . $RandomTimeStamp . $Remark1 . $Remark2 . $Remark3 . $ReturnURL . $NotifyURL;
        if ($this->common->getAntiState() == 1) {
            $dataStr = strtoupper(md5($dataStr));
        }
        $SignInfo = $this->rsa->sign($dataStr);

        $LoanJsonList = urlencode($LoanJsonList);

        $officialAction = MONEYMOREMOREURL . "/loan/loan.action";

        echo "<form id=\"formu\" name=\"formu\" action=\"" . $officialAction . "\" method=\"post\">";
        echo "<input id=\"LoanJsonList\" name=\"LoanJsonList\" value=\"" . $LoanJsonList . "\" type=\"hidden\" />";
        echo "<input id=\"PlatformMoneymoremore\" name=\"PlatformMoneymoremore\" value=\"" . $PlatformMoneymoremore . "\" type=\"hidden\" />";
        echo "<input id=\"TransferAction\" name=\"TransferAction\" value=\"" . $TransferAction . "\" type=\"hidden\" />";
        echo "<input id=\"Action\" name=\"Action\" value=\"" . $Action . "\" type=\"hidden\" />";
        echo "<input id=\"TransferType\" name=\"TransferType\" value=\"" . $TransferType . "\" type=\"hidden\" />";
        echo "<input id=\"NeedAudit\" name=\"NeedAudit\" value=\"" . $NeedAudit . "\" type=\"hidden\" />";
        echo "<input id=\"RandomTimeStamp\" name=\"RandomTimeStamp\" value=\"" . $RandomTimeStamp . "\" type=\"hidden\" />";
        echo "<input id=\"Remark1\" name=\"Remark1\" value=\"" . $Remark1 . "\" type=\"hidden\" />";
        echo "<input id=\"Remark2\" name=\"Remark2\" value=\"" . $Remark2 . "\" type=\"hidden\" />";
        echo "<input id=\"Remark3\" name=\"Remark3\" value=\"" . $Remark3 . "\" type=\"hidden\" />";
        echo "<input id=\"ReturnURL\" name=\"ReturnURL\" value=\"" . $ReturnURL . "\" type=\"hidden\" />";
        echo "<input id=\"NotifyURL\" name=\"NotifyURL\" value=\"" . $NotifyURL . "\" type=\"hidden\" />";
        echo "<input id=\"SignInfo\" name=\"SignInfo\" value=\"" . $SignInfo . "\" type=\"hidden\" />";
        echo "<script language=\"javascript\">window.onload=function(){document.formu.submit();}</script>";
        echo "</form>";
    }

    public function transfercreditorreturn() {
        $this->load->library('/mmm/Rsa', 'rsa');
        $this->load->library('/mmm/Common', 'common');
        $this->load->library('/mmm/LoanInfoBean', 'loaninfobean');
        $this->load->library('/mmm/LoanInfoSecondaryBean', 'loaninfosecondarybean');

        $LoanJsonList = $_POST["LoanJsonList"];
        $LoanJsonList = urldecode($LoanJsonList);
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];

        $dataStr = $LoanJsonList . $PlatformMoneymoremore . $RandomTimeStamp . $Remark1 . $Remark2 . $Remark3 . $ResultCode;
        if ($this->common->getAntiState() == 1) {
            $dataStr = strtoupper(md5($dataStr));
        }
        $verifySignature = $this->rsa->verify($dataStr, $SignInfo);
        if ($ResultCode == 88) {
            $returnJson = json_decode(urldecode($LoanJsonList), true);
            $LoanNo = $returnJson[0]['LoanNo'];

            $paranmstr = explode("#", $Remark2);
            $data['obj_id'] = $paranmstr[0];
            /* $data['tender_id'] 			= $paranmstr[1];
              $data['fstatus'] 			= $paranmstr[2];
              $data['user_id'] 			= $paranmstr[3];
              $data['discount_account'] 	= $paranmstr[4];
              $data['discount_buy'] 		= $paranmstr[5];
              $data['repay_account'] 		= $paranmstr[6];
              $data['repay_yesaccount'] 	= $paranmstr[7];
              $data['mmm_loanno'] 		= $LoanNo;
              $data['add_time'] 			= time();
              $this->load->model('Creditor_model');
              $this->Creditor_model->creditor_transfer($data); */
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo "<script>alert('SUCCESS');window.location.href='/borrow/creditor/" . $data['obj_id'] . "';</script>";
        } else {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo $Message;
        }
    }

    public function transfercreditornotify() {
        $this->load->library('/mmm/Rsa', 'rsa');
        $this->load->library('/mmm/Common', 'common');
        $this->load->library('/mmm/LoanInfoBean', 'loaninfobean');
        $this->load->library('/mmm/LoanInfoSecondaryBean', 'loaninfosecondarybean');

        $LoanJsonList = $_POST["LoanJsonList"];
        $LoanJsonList = urldecode($LoanJsonList);
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];

        $dataStr = $LoanJsonList . $PlatformMoneymoremore . $RandomTimeStamp . $Remark1 . $Remark2 . $Remark3 . $ResultCode;
        if ($this->common->getAntiState() == 1) {
            $dataStr = strtoupper(md5($dataStr));
        }
        $verifySignature = $this->rsa->verify($dataStr, $SignInfo);
        if ($ResultCode == 88) {
            $returnJson = json_decode(urldecode($LoanJsonList), true);
            $LoanNo = $returnJson[0]['LoanNo'];

            $paranmstr = explode("#", $Remark2);
            $data['obj_id'] = $paranmstr[0];
            $data['tender_id'] = $paranmstr[1];
            $data['fstatus'] = $paranmstr[2];
            $data['user_id'] = $paranmstr[3];
            $data['discount_account'] = $paranmstr[4];
            $data['discount_buy'] = $paranmstr[5];
            $data['repay_account'] = $paranmstr[6];
            $data['repay_yesaccount'] = $paranmstr[7];
            $data['mmm_loanno'] = $LoanNo;
            $data['add_time'] = time();
            $this->load->model('Creditor_model');
            $this->Creditor_model->creditor_transfer($data);
            echo "SUCCESS";
        } else {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo $Message;
        }
    }

    //净值额度计算 净值额度 (代收+可用-待还)*0.8
    function net_value($user_id){
        if(!$user_id){
            return 0;
        }
        $this->load->model('Account_model');
        $this->load->model('Borrow_model');
        $user_account = $this->Account_model->get_account($user_id);
        $tmpMoney = $this->Borrow_model->no_repayment_borrow_3($user_id);
        $money = ($user_account['collection'] + $user_account['use_money'] - $tmpMoney) * CON_BORROW_JIN_CREDIT;
        return $money;
    }

    //借款申请
    public function apply(){
        $vdata['active'] = "borrow";
        $vdata['title'] = "申请" . ' - ' . CON_KEYWORDS;
        $this->load->view('borrow/borrow_apply',$vdata);
    }

    public function apply_post(){
        $data=$_POST;
        $user=$this->session->userdata('zjy_user');
        $data['user_id']=$user['user_id'];
        $data['apply_time']=time();
//        var_dump($data);exit;
        if($data['apply_name']==''||$data['connect_tel']==''||$data['apply_amount']==''){
            echo "<script>alert('请填写完整再提交！');history.back(-1);</script>";exit;
        }
        $this->load->model('Borrow_model','borrow');
        if(!$this->borrow->apply_add($data)){
            echo "<script>alert('提交失败');history.go(-1);</script>";
        } else {
            echo "<script>alert('提交成功！请等待审核。');window.location.href='/borrow/blist';</script>";
        }
    }
}
